import {
  createCategory,
  deleteCategory,
  getCategoryList,
  updateCategory,
  moveCategory,
} from '@/services/category';
import {DeleteOutlined, EditOutlined, FileDoneOutlined, PlusOutlined} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Card, message, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';
import UpdateForm from './components/UpdateForm';
import './index.less';
const TableList: React.FC = (props) => {
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: any) => {
    try {
      const params = {
        ...fields,
        type: 'photo',
      };
      if (!!addRow) {
        params.parentId = addRow.id;
      }
      const res = await createCategory(params);
      if (res.code == '0') {
        message.success('添加成功！');
      }
      await getCategory();
      return true;
    } catch (error) {
      message.error('添加失败!' + error.response.data.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: any) => {
    const params = {
      ...fields,
      id: currentRow.id,
      parentId: currentRow.parentId,
      type: 'photo',
    };
    try {
      const res = await updateCategory(params);
      if (res.code == '0') {
        message.success('更新成功！');
      }
      await getCategory();
      return true;
    } catch (error) {
      message.error('更新失败！' + error.response.data.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record) => {
    try {
      const res = await deleteCategory({
        id: record.id,
      });
      if (res.code == '0') {
        message.success('已删除！');
      }
      getCategory();
      return true;
    } catch (error) {
      message.error('删除失败！' + error.response.data.message);
      return false;
    }
  };

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<any>();

  const [addRow, setAddRow] = useState<any>();

  const [data, setData] = useState([]);

  const [isAdd, setIsAdd] = useState<boolean>(true);
  //查询分类
  const getCategory = () => {
    const params = {
      type: 'photo',
    };
    //获取组list
    getCategoryList(params).then(async (res) => {
      setData(res.data);
    });
  };
  useEffect(() => {
    getCategory();
  }, []);

  //移动分类
  const moveAction = async (id, operation) => {
    const res = await moveCategory({
      id,
      operation,
    });
    if (res.code == '0') {
      message.success('移动成功！');
      getCategory();
    }
  };
  const columns: any = [
    {
      title: '类别名称',
      dataIndex: 'name',
      key: 'name',
      width: '30%',
      render: (_, record) => {
        if (!record.parentId) {
          return (
            <div className="centerTableName">
              <div className="left">{record.name}</div>
              <div
                className="right"
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setAddRow(record);
                }}
              >
                添加子类
              </div>
            </div>
          );
        } else {
          return <div className="left">{record.name}</div>;
        }
      },
    },
    {
      title: '分类说明',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'description',
    },
    {
      title: '操作',
      align: 'left',
      dataIndex: 'option',
      width: '20%',
      render: (_, record) => {
        if (!record.parentId) {
          return (
            <Space>
              <a
                style={{ color: '#1677ff' }}
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setCurrentRow(record);
                  setIsAdd(false);
                }}
              >
                <Button className={'buttonMargin'} shape={'round'} icon={<EditOutlined />}>
                  编辑
                </Button>
              </a>
              <a
                style={{ color: 'red' }}
                onClick={() => {
                  handleRemove(record);
                }}
              >
                <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
                  删除
                </Button>
              </a>
            </Space>
          );
        } else {
          return (
            <Space>
              <a
                style={{ color: '#1677ff' }}
                onClick={() => {
                  handleUpdateModalVisible(true);
                  setCurrentRow(record);
                  setIsAdd(false);
                }}
              >
                <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
                  编辑
                </Button>
              </a>
              <a
                style={{ color: 'red' }}
                onClick={() => {
                  handleRemove(record);
                }}
              >
                <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
                  删除
                </Button>
              </a>
              <a style={{ color: '#ccc' }} onClick={() => moveAction(record.id, 'up')}>
                上移
              </a>
              <a style={{ color: '#ccc' }} onClick={() => moveAction(record.id, 'down')}>
                下移
              </a>
            </Space>
          );
        }
      },
    },
  ];

  return (
    <PageContainer
      header={{
        title: false,
      }}
    >
      <Card title="">
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleUpdateModalVisible(true);
              setIsAdd(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined />
            添加
          </Button>
          <Table columns={columns} dataSource={data} rowKey={'id'} />
        </Space>
      </Card>
      <UpdateForm
        addType={isAdd}
        onSubmit={async (value) => {
          //判断id是否存在，判断新建/边界
          let success;
          if (isAdd) {
            success = await handleAdd(value);
          } else {
            success = await handleUpdate(value);
          }
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            setAddRow(undefined);
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
        key={new Date().getTime()}
      />
    </PageContainer>
  );
};

export default TableList;
